package com.weifly.weistock.web.controller.record;

import com.weifly.weistock.core.common.ErrorCode;
import com.weifly.weistock.core.common.Result;
import com.weifly.weistock.record.RecordUtils;
import com.weifly.weistock.record.base.domain.MergeRecordResult;
import com.weifly.weistock.record.bill.BillMonitorService;
import com.weifly.weistock.record.bill.BillParseService;
import com.weifly.weistock.record.bill.domain.GetStockRecordRequest;
import com.weifly.weistock.record.bill.domain.StockRecordDto;
import com.weifly.weistock.record.bill.domain.StockSummaryDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 股票记录
 *
 * @author weifly
 * @since 2020/01/17
 */
@Controller
@RequestMapping(value = "/record/bill")
public class BillMonitorController {

    private Logger log = LoggerFactory.getLogger(BillMonitorController.class);

    @Autowired
    private BillParseService billParseService;

    @Autowired
    private BillMonitorService billMonitorService;

    /**
     * 记录首页
     */
    @RequestMapping(value = "/index")
    public String index(HttpServletRequest request, HttpServletResponse response) {
        return "record/bill/index";
    }

    /**
     * 导入对账单
     */
    @RequestMapping(value = "/import")
    public String importOrder(HttpServletRequest request, HttpServletResponse response) {
        return "record/bill/import";
    }

    /**
     * 上传交割单
     */
    @ResponseBody
    @RequestMapping("/uploadStockOrder")
    public Result uploadStockOrder(MultipartHttpServletRequest request) {
        try{
            MultipartFile orderFile = request.getFile("stockOrderFile");
            if(orderFile==null || orderFile.isEmpty()){
                return new Result(ErrorCode.RESULT_PARAM_ERROR, "请上传对账单文件");
            }

            List<StockRecordDto> recordList = this.billParseService.parseRecord(orderFile.getInputStream());
            MergeRecordResult mergeResult = this.billMonitorService.mergeRecordList(recordList);
            return Result.createSuccessResult(mergeResult);
        }catch(Exception e){
            log.error("处理提交数据出错", e);
            return Result.createErrorResult("处理出错: "+e.getMessage());
        }
    }

    /**
     * 股票列表
     */
    @RequestMapping(value = "/stockList")
    public String stockList(HttpServletRequest request, HttpServletResponse response) {
        return "record/bill/stockList";
    }

    /**
     * 加载股票列表
     */
    @ResponseBody
    @RequestMapping("/getStockList")
    public Result getStockList(HttpServletRequest request){
        try{
            // 获取股票列表 并排序
            List<StockSummaryDto> stockList = this.billMonitorService.getStockList();
            stockList.sort((d1, d2)->{
                String time1 = this.getLastOrderTime(d1);
                String time2 = this.getLastOrderTime(d2);
                return time2.compareTo(time1);
            });

            // 转换数据
            List<Map<String, Object>> infoList = new ArrayList<>();
            for(int i=0;i<stockList.size();i++){
                StockSummaryDto summaryDto = stockList.get(i);
                Map<String, Object> recordInfo = new HashMap<>();
                recordInfo.put("stockCode", summaryDto.getStockCode());
                recordInfo.put("stockName", summaryDto.getStockName());
                recordInfo.put("recordSize", summaryDto.getRecordList().size()); // 交易次数
                recordInfo.put("diffAmount", summaryDto.getDiffAmount()); // 差额
                recordInfo.put("feeService", summaryDto.getFeeService()); // 手续费
                recordInfo.put("feeStamp", summaryDto.getFeeStamp()); // 印花税
                recordInfo.put("afterNumber", summaryDto.getAfterNumber()); // 剩余数量
                recordInfo.put("lastOrderTime", this.getLastOrderTime(summaryDto)); // 最后交易时间
                infoList.add(recordInfo);
            }
            return Result.createSuccessResult(infoList);
        }catch(Exception e){
            log.error("加载股票列表出错", e);
            return Result.createErrorResult("加载股票列表出错: " + e.getMessage());
        }
    }

    private String getLastOrderTime(StockSummaryDto summaryDto){
        String lastOrderTime = "";
        if(summaryDto.getRecordList().size()>0){
            StockRecordDto lastRecord = summaryDto.getRecordList().get(summaryDto.getRecordList().size()-1);
            lastOrderTime = lastRecord.getDate() + " " + lastRecord.getTime();
        }
        return lastOrderTime;
    }

    /**
     * 交易记录列表
     */
    @RequestMapping(value = "/recordList")
    public String recordList(HttpServletRequest request, HttpServletResponse response) {
        String stockCode = request.getParameter("stockCode"); // 股票代码
        StockSummaryDto summaryDto = this.billMonitorService.getStockSummary(stockCode);
        if(summaryDto==null){
            summaryDto = new StockSummaryDto();
        }
        Map<String, Object> fieldMap = new HashMap<>();
        fieldMap.put("stockCode", (summaryDto.getStockCode()==null ? "" : summaryDto.getStockCode()));
        fieldMap.put("stockName", (summaryDto.getStockName()==null ? "" : summaryDto.getStockName()));
        fieldMap.put("recordSize", summaryDto.getRecordList().size());
        fieldMap.put("diffAmount", (summaryDto.getDiffAmount()==null ? "" : summaryDto.getDiffAmount()));
        fieldMap.put("feeService", (summaryDto.getFeeService()==null ? "" : summaryDto.getFeeService()));
        fieldMap.put("feeStamp", (summaryDto.getFeeStamp()==null ? "" : summaryDto.getFeeStamp()));
        fieldMap.put("afterNumber", (summaryDto.getAfterNumber()==null ? "" : summaryDto.getAfterNumber()));
        request.setAttribute("stockSummary", fieldMap);
        return "record/bill/recordList";
    }

    /**
     * 加载交易记录列表
     */
    @ResponseBody
    @RequestMapping("/getRecordList")
    public Result getRecordList(HttpServletRequest request){
        try{
            String stockCode = request.getParameter("stockCode"); // 股票代码
            String date = request.getParameter("date"); // 发生日期
            String time = request.getParameter("time"); // 成交时间
            String entrust = request.getParameter("entrust"); // 委托编号
            int limit = 100;

            // 取记录列表
            GetStockRecordRequest queryRequest = new GetStockRecordRequest();
            queryRequest.setStockCode(stockCode);
            queryRequest.setDate(date);
            queryRequest.setTime(time);
            queryRequest.setEntrust(entrust);
            queryRequest.setLimit(limit+1);
            List<StockRecordDto> recordList = this.billMonitorService.getRecordList(queryRequest);

            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("haveMore", recordList.size()>limit);

            List<Map<String, Object>> recordInfoList = new ArrayList<>();
            if(recordList.size()>0){
                for(int i=0;i<recordList.size();i++){
                    StockRecordDto recordDto = recordList.get(i);
                    Map<String, Object> recordInfo = new HashMap<>();
                    recordInfo.put("date", recordDto.getDate());
                    recordInfo.put("time", recordDto.getTime());
                    recordInfo.put("entrustCode", recordDto.getEntrustCode());
                    recordInfo.put("businessName", recordDto.getBusinessName().getName());
                    recordInfo.put("tradePrice", recordDto.getTradePrice());
                    recordInfo.put("tradeNumber", recordDto.getTradeNumber());
                    recordInfo.put("tradeAmount", recordDto.getTradeAmount());
                    recordInfo.put("feeService", recordDto.getFeeService());
                    recordInfo.put("feeStamp", recordDto.getFeeStamp());
                    recordInfo.put("clearAmount", recordDto.getClearAmount());
                    recordInfo.put("diffAmount", recordDto.getDiffAmount());
                    recordInfo.put("pair", RecordUtils.makePairAttr(recordDto.getPairList(), recordDto.getTradeNumber()));
                    recordInfoList.add(recordInfo);
                }
                // 只返回limit条记录
                if(recordInfoList.size()>limit){
                    recordInfoList = recordInfoList.subList(0, limit);
                }
            }
            dataMap.put("recordList", recordInfoList);

            return Result.createSuccessResult(dataMap);
        }catch(Exception e){
            log.error("加载交易记录列表出错", e);
            return Result.createErrorResult("加载交易记录列表出错: " + e.getMessage());
        }
    }
}
